package cn.edu.scau.cmi.yangmupei.hibernate.service;

import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.edu.scau.cmi.yangmupei.hibernate.dao.TeacherDAO;
import cn.edu.scau.cmi.yangmupei.hibernate.domain.Student;
import cn.edu.scau.cmi.yangmupei.hibernate.domain.Teacher;

public class TeacherService {

	private Session session;
	private TeacherDAO teacherDAO;
	private Transaction transaction;
	
	public TeacherService() {}
	public TeacherService(Session session) {
		this.session = session;
		teacherDAO = new TeacherDAO(this.session);
	}
	
	public void saveTeacher(Teacher teacher) {
		transaction = session.beginTransaction();
		teacherDAO.save(teacher);
		System.out.println("添加教师成功!");
		transaction.commit();
	}
	
	public void updateTeacher(Teacher teacher) {
		transaction = session.beginTransaction();
		teacherDAO.update(teacher);
		System.out.println("修改教师成功！");
		transaction.commit();
	}
	
	public void deleteTeacher(Teacher teacher) {
		transaction = session.beginTransaction();
		teacherDAO.delete(teacher);
		session.flush();
		session.evict(teacher);
		System.out.println("删除教师成功！");
		transaction.commit();
	}
	
	public void select(Student student,Teacher tutor,int flag) {
		transaction = session.beginTransaction();
		Student stu = (Student) session.get(Student.class, student.getId());
		Teacher t = (Teacher) session.get(Teacher.class, tutor.getId());
		t.getStudents().add(stu);
		stu.setTutor(t);
		if(flag == 9) {
			System.out.println("教师选择被指导的学生成功！");
		}else if(flag == 10) {
			System.out.println("教师修改被指导的学生成功!");
		}
		transaction.commit();
	}
}
